<?php
declare (strict_types = 1);

namespace app\command\Shopify;

use app\constant\CommonConstant;
use app\event\PushOrderToShopify;
use app\model\Notify;
use app\model\Orders;
use app\model\Shops;
use app\model\ShopsPayment;
use app\service\shopify\action\rest\DraftOrderRest;
use app\trait\OrderTrait;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\Exception;
use think\facade\Event;
use think\helper\Arr;
use think\helper\Str;
use function Clue\StreamFilter\fun;

class QuickPayFixed extends Command
{
    use OrderTrait;
    protected $shopList;
    protected function configure()
    {
        // 指令配置
        $this->setName('quickpay:fixed')
            ->addOption('trade_no','trade_no',Option::VALUE_OPTIONAL,'交易号')
            ->addOption('id','id',Option::VALUE_OPTIONAL,'ID')
            ->setDescription('修复快捷支付');
    }

    protected function execute(Input $input, Output $output)
    {
        $options = $input->getOptions();
        $this->shopList = Shops::query()
            //->where('id',23)
            ->whereNotIn('id',[1,2,5])
            ->select();
       # 获取所有快捷支付
        $notifys = Notify::query()
            ->where('type',Notify::TYPE_DRAFT_QUICK_PAY)
            ->when(isset($options['trade_no']) && !empty($options['trade_no']),function ($q) use ($options){
                return $q->where('params','like',"%". $options['trade_no'] .'%');
            })
            ->when(isset($options['id']) && !empty($options['id']),function ($q) use ($options){
                return $q->where('id',$options['id']);
            })
            ->select();
        #过滤已经处理的快捷支付

        if($notifys->isEmpty()) return false;
        $filters = [];
        foreach ($notifys as $notify){
            $params = $notify->params;
            $request = $params['request'] ?? [];
            if(empty($request)) continue;
            $paypal = Arr::get($request,'paypal',[]);
            if(empty($paypal)) continue;
            $orderNo = Arr::get($paypal,'id','');
            if(empty($orderNo)) continue;
            dump('****************orderNo: '.$orderNo.'**********');
            $orders = Orders::query()->where('order_no','like','%'.$orderNo.'%')->select();
            if(!$orders->isEmpty()) continue;
            $filters[] = $notify;
        }
        if(empty($filters)) return false;
        dump('总数: ' . count($filters));
        foreach ($filters as $filter){
            try{
               $this->handleShopifyOrder($filter);
            }catch (\Exception $e){
                dump($e);
            }
        }
    }

    protected function handleShopifyOrder(Notify $notify)
    {
        $params = $notify->params;
        $request = Arr::get($params,'request',[]);
        if(empty($request)) throw new \Exception('request 参数错误');
        $paypal = Arr::get($request,'paypal',[]);
        if(empty($paypal)) throw new \Exception('paypal 参数错误');
        $orderNo = Arr::get($paypal,'id');
        dump('**********************正在处理快捷支付: '.$orderNo.'**************');
        $checkout= Arr::get($request,'checkout',[]);
        if(empty($checkout)) throw new \Exception('checkout 参数错误');
        $items = $checkout['cart']['items'] ?? [];
        if(empty($items)) throw new \Exception('items 参数错误');
        $item = Arr::first($items);
        $url = Arr::get($item,'url','');
        if(empty($url)) throw new \Exception('items url 参数错误');
        //查域名
       $productList = $this->getShopByProductUrl($url);
        if(empty($productList)){
            dump("快捷支付not found 店铺: ' . $orderNo");
            tplog('快捷支付not found 店铺: ' . $orderNo,['notifyId'=>$notify->id,'order_no'=>$orderNo],'shopify');
        }else{
            //推shopify
            $this->pushToShopify($notify,$productList);
        }

    }



    protected function getShopByProductUrl($urlPath)
    {
        if(Str::contains($urlPath,'?')){
            $urlPath = Arr::first(explode('?',$urlPath));
        }
        $urlPath .= '.json';
        $opts = [
            'http' => [
                'header' => "User-Agent: Mozilla/5.0\n" .
                    "Accept-Language: en-US,en;q=0.5\n",
            ],
        ];
        $context = stream_context_create($opts);
       $productList = [];
        foreach ($this->shopList as $shop){
            try {
                $productUrl = sprintf('https://%s%s', $shop->host, $urlPath);
                dump($productUrl);
                $content = file_get_contents($productUrl, false, $context);
                if($productData = json_decode($content,true)){
                    dump(['shopify商品'=>$productData]);
                    $productId = $productData['product']['id'];
                    $productList[$productId] = [
                        'shop'=>$shop,
                        'product'=>$productData['product']
                    ];
                }
            }catch (\Exception $e){
                dump($e->getMessage());
            }
        }
        return $productList;
    }

    public function pushToShopify(Notify $notify,array $productList)
    {
        $request = Arr::get($notify->params,'request',[]);
        if(empty($request)) throw new \Exception('request 参数错误');
        $checkout = Arr::get($request,'checkout',[]);
        $paypal = Arr::get($request,'paypal',[]);
        if (empty($checkout) && empty($paypal)) throw new \Exception('checkout paypal 参数错误');
        $items = $checkout['cart']['items'];
        $line_items = $this->setLineItems($items);
        $lineItem = Arr::first($line_items);
        dump($lineItem);
        $productId = Arr::get($lineItem,'product_id');
        //dd($productId);
        $productData = $productList[$productId] ?? [];
        if(empty($productData)){
            $productData = Arr::first($productList);
        }
        $shop = $productData['shop'];
        $productList = $productData['product'];
        $variants = $productList['variants'] ?? [];
        //dd($shop,$variants);
        if(empty($variants)) throw new \Exception('variants 参数错误');
        $variantsIds = array_column($variants,'id');
        //查看变体是否存在
        if(count($line_items) < 2) {//只能判断单个商品
            foreach ($line_items as &$item) {
                $variantTitle = strtolower($item['variant_title']);
                if (!in_array($item['variant_id'], $variantsIds)) {
                    foreach ($variants as $variant) {
                        $percent = 0;
                        similar_text($variantTitle, $variant['title'], $percent);
                        dump($percent);
                        if ($percent >= 45) {
                            $item['variant_id'] = $variant['id'];
                            $item['product_id'] = $variant['product_id'];
                            break;
                        }
                    }
                }
            }
        }
        $customer = $this->setCustomer($paypal);
        $shipping_line =  Arr::get($request,'shipping_line', []);
        if ($shipping_line) unset($shipping_line['origin_price']);
        $draftParams = [
            'line_items' => $line_items,
            'shipping_line' => $shipping_line,
            'email' => $customer['email'],
            'shipping_address' => $customer['shipping_address'],
            'billing_address' => $customer['shipping_address'],
        ];
        dump(['草稿参数'=>$draftParams]);
        try {
            $rest = new DraftOrderRest($shop->id);
            $draft = $rest->create_draft_order($draftParams);//创建草稿订单
            //dump($draft);
            $draft['order_no'] = $customer['order_no'];
            $draft['transaction_id'] = $customer['transaction_id'];
            $draft['payment_id'] = ShopsPayment::where('shop_id', $shop->id)->where('pay_method', ShopsPayment::PAY_METHOD_PAYPAL)->value('id');
            $draft['payer'] = $customer;
            $draft['pay_status'] = $customer['pay_status'];
            $place_order_result[CommonConstant::FIRST_PAY_KEY] = $paypal;
            $draft['place_order_result'] = $place_order_result;
            $draft['is_paypal_kj'] = Orders::IS_PAYPAL_KJ_Y;
            $draft['shop_id'] = $shop->id;
            $order = $this->saveDraftOrder($draft, $request);
            dump('订单ID: ' . $order->id);
            //推送订单到通途
            Event::trigger("PushOrder", new PushOrderToShopify($order));
        }catch (\Exception $e){
            dump("创建快捷支付失败: ' . $notify->id: ",$e->getMessage());
            tplog('快捷支付失败: ' .$notify->id ,['notifyId'=>$notify->id,'order_no'=>Arr::get($paypal,'id',''),'shop_id'=>$shop->id,'host'=>$shop->host],'shopify');
        }
    }

}
